{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>\n",
       "/* 本电子讲义使用之CSS */\n",
       "div.code_cell {\n",
       "    background-color: #e5f1fe;\n",
       "}\n",
       "div.cell.selected {\n",
       "    background-color: #effee2;\n",
       "    font-size: 2rem;\n",
       "    line-height: 2.4rem;\n",
       "}\n",
       "div.cell.selected .rendered_html table {\n",
       "    font-size: 2rem !important;\n",
       "    line-height: 2.4rem !important;\n",
       "}\n",
       ".rendered_html pre code {\n",
       "    background-color: #C4E4ff;   \n",
       "    padding: 2px 25px;\n",
       "}\n",
       ".rendered_html pre {\n",
       "    background-color: #99c9ff;\n",
       "}\n",
       "div.code_cell .CodeMirror {\n",
       "    font-size: 2rem !important;\n",
       "    line-height: 2.4rem !important;\n",
       "}\n",
       ".rendered_html img, .rendered_html svg {\n",
       "    max-width: 60%;\n",
       "    height: auto;\n",
       "    float: right;\n",
       "}\n",
       "\n",
       ".rendered_html img[src*=\"#full\"], .rendered_html svg[src*=\"#full\"] {\n",
       "    max-width: 100%;\n",
       "    height: auto;\n",
       "    float: none;\n",
       "}\n",
       "\n",
       ".rendered_html img[src*=\"#thumbnail\"], .rendered_html svg[src*=\"#thumbnail\"] {\n",
       "    max-width: 15%;\n",
       "    height: auto;\n",
       "}\n",
       "\n",
       "/* Gradient transparent - color - transparent */\n",
       "hr {\n",
       "    border: 0;\n",
       "    border-bottom: 1px dashed #ccc;\n",
       "}\n",
       ".emoticon{\n",
       "    font-size: 5rem;\n",
       "    line-height: 4.4rem;\n",
       "    text-align: center;\n",
       "    vertical-align: middle;\n",
       "}\n",
       ".bg-split_apply_comine {\n",
       "    width: 500px;     \n",
       "    height: 300px;\n",
       "    background: url('02_split-apply-comine_500x300.png') -10px -10px;\n",
       "    float: right;\n",
       "}\n",
       ".bg-comine {\n",
       "    width: 175px;\n",
       "    height: 150px;\n",
       "    background: url('02_split-apply-comine_500x300.png') -280px -80px;\n",
       "    float: right;\n",
       "}\n",
       ".bg-apply {\n",
       "    width: 155px;\n",
       "    height: 225px;\n",
       "    background: url('02_split-apply-comine_500x300.png') -160px -30px;\n",
       "    float: right;\n",
       "}\n",
       ".bg-split {\n",
       "    width: 205px;\n",
       "    height: 225px;\n",
       "    background: url('02_split-apply-comine_500x300.png') -10px -30px;\n",
       "    float: right;\n",
       "}\n",
       ".break {\n",
       "                   page-break-after: right; \n",
       "                   width:700px;\n",
       "                   clear:both;\n",
       "}\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%html\n",
    "<style>\n",
    "/* 本电子讲义使用之CSS */\n",
    "div.code_cell {\n",
    "    background-color: #e5f1fe;\n",
    "}\n",
    "div.cell.selected {\n",
    "    background-color: #effee2;\n",
    "    font-size: 2rem;\n",
    "    line-height: 2.4rem;\n",
    "}\n",
    "div.cell.selected .rendered_html table {\n",
    "    font-size: 2rem !important;\n",
    "    line-height: 2.4rem !important;\n",
    "}\n",
    ".rendered_html pre code {\n",
    "    background-color: #C4E4ff;   \n",
    "    padding: 2px 25px;\n",
    "}\n",
    ".rendered_html pre {\n",
    "    background-color: #99c9ff;\n",
    "}\n",
    "div.code_cell .CodeMirror {\n",
    "    font-size: 2rem !important;\n",
    "    line-height: 2.4rem !important;\n",
    "}\n",
    ".rendered_html img, .rendered_html svg {\n",
    "    max-width: 60%;\n",
    "    height: auto;\n",
    "    float: right;\n",
    "}\n",
    "\n",
    ".rendered_html img[src*=\"#full\"], .rendered_html svg[src*=\"#full\"] {\n",
    "    max-width: 100%;\n",
    "    height: auto;\n",
    "    float: none;\n",
    "}\n",
    "\n",
    ".rendered_html img[src*=\"#thumbnail\"], .rendered_html svg[src*=\"#thumbnail\"] {\n",
    "    max-width: 15%;\n",
    "    height: auto;\n",
    "}\n",
    "\n",
    "/* Gradient transparent - color - transparent */\n",
    "hr {\n",
    "    border: 0;\n",
    "    border-bottom: 1px dashed #ccc;\n",
    "}\n",
    ".emoticon{\n",
    "    font-size: 5rem;\n",
    "    line-height: 4.4rem;\n",
    "    text-align: center;\n",
    "    vertical-align: middle;\n",
    "}\n",
    ".bg-split_apply_comine {\n",
    "    width: 500px;     \n",
    "    height: 300px;\n",
    "    background: url('02_split-apply-comine_500x300.png') -10px -10px;\n",
    "    float: right;\n",
    "}\n",
    ".bg-comine {\n",
    "    width: 175px;\n",
    "    height: 150px;\n",
    "    background: url('02_split-apply-comine_500x300.png') -280px -80px;\n",
    "    float: right;\n",
    "}\n",
    ".bg-apply {\n",
    "    width: 155px;\n",
    "    height: 225px;\n",
    "    background: url('02_split-apply-comine_500x300.png') -160px -30px;\n",
    "    float: right;\n",
    "}\n",
    ".bg-split {\n",
    "    width: 205px;\n",
    "    height: 225px;\n",
    "    background: url('02_split-apply-comine_500x300.png') -10px -30px;\n",
    "    float: right;\n",
    "}\n",
    ".break {\n",
    "                   page-break-after: right; \n",
    "                   width:700px;\n",
    "                   clear:both;\n",
    "}\n",
    "</style>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from requests_html import HTMLSession"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "edu         7\n",
      "经验         11\n",
      "薪水         92\n",
      "时间         21\n",
      "职称        187\n",
      "公司地点       62\n",
      "公司名称       62\n",
      "链结        196\n",
      "公司URL      63\n",
      "热门公司类型      6\n",
      "dtype: int64\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>职称</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>公司名称</th>\n",
       "      <th>edu</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>天能电池集团股份有限公司</th>\n",
       "      <th>统招本科</th>\n",
       "      <td>18</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>华为</th>\n",
       "      <th>本科及以上</th>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>恒大集团</th>\n",
       "      <th>硕士及以上</th>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>奥比中光</th>\n",
       "      <th>硕士及以上</th>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>天能电池集团股份有限公司</th>\n",
       "      <th>本科及以上</th>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>广日股份</th>\n",
       "      <th>本科及以上</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>敏实集团</th>\n",
       "      <th>大专及以上</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>新城控股集团住宅开发事业部</th>\n",
       "      <th>本科及以上</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>明略科技集团</th>\n",
       "      <th>统招本科</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>风范股份</th>\n",
       "      <th>本科及以上</th>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>93 rows × 1 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                     职称\n",
       "公司名称          edu      \n",
       "天能电池集团股份有限公司  统招本科   18\n",
       "华为            本科及以上  14\n",
       "恒大集团          硕士及以上  10\n",
       "奥比中光          硕士及以上   9\n",
       "天能电池集团股份有限公司  本科及以上   9\n",
       "...                  ..\n",
       "广日股份          本科及以上   1\n",
       "敏实集团          大专及以上   1\n",
       "新城控股集团住宅开发事业部 本科及以上   1\n",
       "明略科技集团        统招本科    1\n",
       "风范股份          本科及以上   1\n",
       "\n",
       "[93 rows x 1 columns]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "参数_compTag_用户体验 = {'中国500强': {'init': ['-1'], 'headckid': ['58d828c357a8cb19'], 'flushckid': ['1'], 'fromSearchBtn': ['2'], 'keyword': ['用户体验'], 'compTag': ['155'], 'ckid': ['58d828c357a8cb19'], 'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'], 'd_sfrom': ['search_unknown'], 'd_ckId': ['6aa779111c1b4ca77cff3648d9dee049'], 'd_curPage': ['0'], 'd_pageSize': ['40'], 'd_headId': ['6aa779111c1b4ca77cff3648d9dee049']}, '2018互联网300强': {'init': ['-1'], 'headckid': ['58d828c357a8cb19'], 'flushckid': ['1'], 'fromSearchBtn': ['2'], 'keyword': ['用户体验'], 'compTag': ['182'], 'ckid': ['58d828c357a8cb19'], 'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'], 'd_sfrom': ['search_unknown'], 'd_ckId': ['6aa779111c1b4ca77cff3648d9dee049'], 'd_curPage': ['0'], 'd_pageSize': ['40'], 'd_headId': ['6aa779111c1b4ca77cff3648d9dee049']}, '制造业500强': {'init': ['-1'], 'headckid': ['58d828c357a8cb19'], 'flushckid': ['1'], 'fromSearchBtn': ['2'], 'keyword': ['用户体验'], 'compTag': ['186'], 'ckid': ['58d828c357a8cb19'], 'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'], 'd_sfrom': ['search_unknown'], 'd_ckId': ['6aa779111c1b4ca77cff3648d9dee049'], 'd_curPage': ['0'], 'd_pageSize': ['40'], 'd_headId': ['6aa779111c1b4ca77cff3648d9dee049']}, 'AI创新成长50强 ': {'init': ['-1'], 'headckid': ['58d828c357a8cb19'], 'flushckid': ['1'], 'fromSearchBtn': ['2'], 'keyword': ['用户体验'], 'compTag': ['189'], 'ckid': ['58d828c357a8cb19'], 'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'], 'd_sfrom': ['search_unknown'], 'd_ckId': ['6aa779111c1b4ca77cff3648d9dee049'], 'd_curPage': ['0'], 'd_pageSize': ['40'], 'd_headId': ['6aa779111c1b4ca77cff3648d9dee049']}, '独角兽': {'init': ['-1'], 'headckid': ['58d828c357a8cb19'], 'flushckid': ['1'], 'fromSearchBtn': ['2'], 'keyword': ['用户体验'], 'compTag': ['130'], 'ckid': ['58d828c357a8cb19'], 'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'], 'd_sfrom': ['search_unknown'], 'd_ckId': ['6aa779111c1b4ca77cff3648d9dee049'], 'd_curPage': ['0'], 'd_pageSize': ['40'], 'd_headId': ['6aa779111c1b4ca77cff3648d9dee049']}, '上市公司': {'init': ['-1'], 'headckid': ['58d828c357a8cb19'], 'flushckid': ['1'], 'fromSearchBtn': ['2'], 'keyword': ['用户体验'], 'compTag': ['156'], 'ckid': ['58d828c357a8cb19'], 'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'], 'd_sfrom': ['search_unknown'], 'd_ckId': ['6aa779111c1b4ca77cff3648d9dee049'], 'd_curPage': ['0'], 'd_pageSize': ['40'], 'd_headId': ['6aa779111c1b4ca77cff3648d9dee049']}}\n",
    "\n",
    "# 国500强\n",
    "url = \"https://www.liepin.com/zhaopin/\"\n",
    "session = HTMLSession()\n",
    "payload = 参数_compTag_用户体验['中国500强']\n",
    "r = session.get( url, params = payload)\n",
    "\n",
    "session = HTMLSession()\n",
    "\n",
    "def requests_liepin( url, params):\n",
    "    r = session.get( url , params = payload)\n",
    "\n",
    "    主要元素 = r.html.xpath( '//ul[@class=\"sojob-list\"]/li')\n",
    "    dict_xpaths={ \n",
    "        'text': {\n",
    "            'edu':      '//div[contains(@class,\"job-info\")]/p/span[@class=\"edu\"]',\n",
    "            '经验':      '//div[contains(@class,\"job-info\")]/p/span[@class=\"edu\"]/following-sibling::span',\n",
    "            '薪水':    '//div[contains(@class,\"job-info\")]/p/span[@class=\"text-warning\"]', \n",
    "            '时间':    '//div[contains(@class,\"job-info\")]/p/time/@title', \n",
    "            '职称':    '//div[contains(@class,\"job-info\")]/h3/a', \n",
    "            '公司地点': '//div[contains(@class,\"job-info\")]/p/a',\n",
    "            '公司名称': '//div[contains(@class,\"sojob-item-main\")]//p[@class=\"company-name\"]/a', \n",
    "        },\n",
    "        'text_content': {\n",
    "        },\n",
    "        'href': {\n",
    "            '链结':    '//div[contains(@class,\"job-info\")]/h3/a', \n",
    "            '公司URL': '//div[contains(@class,\"sojob-item-main\")]//p[@class=\"company-name\"]/a', \n",
    "        }\n",
    "    }\n",
    "\n",
    "    def get_e_text_content(_xpath_):\n",
    "        # 高级列表推导\n",
    "        暂存结果 = [e.xpath(_xpath_)[0].lxml.text_content() for e in 主要元素]\n",
    "        return(暂存结果)\n",
    "\n",
    "    def get_e_text(_xpath_):\n",
    "        # 高级列表推导\n",
    "        暂存结果 = [\"\".join([x.strip() if type(x) is str else x.text.strip() for x in e.xpath(_xpath_)]) for e in 主要元素]\n",
    "        return(暂存结果)\n",
    "\n",
    "    def get_e_href(_xpath_):\n",
    "        # 高级列表推导\n",
    "        暂存结果 = [list(e.xpath(_xpath_, first=True).absolute_links)[0] \\\n",
    "                   if len(e.xpath(_xpath_, first=True).absolute_links) >= 1  \\\n",
    "                   else \"\" for e in 主要元素]\n",
    "        return(暂存结果)\n",
    "\n",
    "    # 只对主要元素下进行.xpath取值\n",
    "    数据字典 = dict()\n",
    "\n",
    "    数据字典 = {k:get_e_text_content(v) for k,v in dict_xpaths['text_content'].items()}\n",
    "    数据字典.update({k:get_e_text(v) for k,v in dict_xpaths['text'].items()})\n",
    "    数据字典.update({k:get_e_href(v) for k,v in dict_xpaths['href'].items()})\n",
    "\n",
    "    数据 = pd.DataFrame(数据字典)\n",
    "    return (数据)\n",
    "\n",
    "\n",
    "# 多个页面\n",
    "url = \"https://www.liepin.com/zhaopin/\"\n",
    "\n",
    "list_df = list()\n",
    "for k,v in 参数_compTag_用户体验.items():\n",
    "    payload = v\n",
    "    df = requests_liepin( url, params = payload)\n",
    "    df = df.assign (热门公司类型 = k)    \n",
    "    list_df.append(df)\n",
    "\n",
    "df_all = pd.concat(list_df)\n",
    "df_all\n",
    "\n",
    "# 输出\n",
    "df_all.to_excel(\"20春_Web数据挖掘_week03_liepin_各热门公司类型.xlsx\", sheet_name=\"搜查结果\")\n",
    "\n",
    "# Pandas  基本能力\n",
    "\n",
    "print (df_all.nunique())\n",
    "df_all[['edu']].drop_duplicates()\n",
    "\n",
    "df_all.groupby(['公司名称','edu']).agg({\"职称\":\"count\"}).sort_values(by='职称', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 单一页面\n",
    "url = \"https://www.liepin.com/zhaopin/?keyword=PRD\"\n",
    "session = HTMLSession()\n",
    "r = session.get( url )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[<Element 'a' href='/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=1'>, <Element 'a' href='/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=2'>, <Element 'a' href='/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=3'>, <Element 'a' href='/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=4'>, <Element 'a' href='/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=1'>, <Element 'a' class=('last',) href='/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=9' title='末页'>]\n",
      "{'2': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=1', '3': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=2', '4': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=3', '5': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=4', '下一页': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=1', '': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=9'}\n"
     ]
    }
   ],
   "source": [
    "# xpath 解析翻页a/@href\n",
    "xpath_翻页a = '//div[@class=\"pagerbar\"]/a' # 有disabled, current等href是javascript\n",
    "xpath_翻页a = '//div[@class=\"pagerbar\"]/a[starts-with(@href,\"/zhaopin\")]'\n",
    "print (r.html.xpath(xpath_翻页a)) # 物件\n",
    "\n",
    "href_列表 = [x.xpath('//@href')[0] for x in r.html.xpath(xpath_翻页a)]\n",
    "#print (href_列表)\n",
    "\n",
    "文字_列表 = [x.text for x in r.html.xpath(xpath_翻页a)]\n",
    "#print (文字_列表)\n",
    "\n",
    "href_字典 = {x.text:x.xpath('//@href')[0]  for x in r.html.xpath(xpath_翻页a)}\n",
    "print (href_字典)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "## 建构参数模板\n",
    "\n",
    "```python\n",
    "\n",
    "# 使用 urllib.parse 解析\n",
    "from urllib.parse import urlparse, parse_qs\n",
    "\n",
    "\n",
    "# 使用 pd.DataFrame进行 unuinque()相异值计量比对 \n",
    "import pandas as pd\n",
    "df = pd.DataFrame([ urlparse(x) for x in 公司数据选择器链结.values()])\n",
    "print(df.nunique())\n",
    "\n",
    "# 针对query 再解析之 \n",
    "#df_qs = pd.DataFrame([ parse_qs(x) for x in df['query'] ])\n",
    "df_qs = pd.DataFrame([{k:v[0] for k,v in parse_qs(x).items()} for x in df['query'] ])\n",
    "print(df.nunique())\n",
    "\n",
    "# 建构 参数模板 及 字典_compTag\n",
    "def parse_url_qs_for_compTag (url):\n",
    "    six_parts = urlparse(url) \n",
    "    out = parse_qs(six_parts.query)\n",
    "    return (out)\n",
    "\n",
    "# parse_url_qs_for_compTag(list(公司数据选择器链结.values())[0])['compTag']\n",
    "参数模板 = parse_url_qs_for_compTag(list(公司数据选择器链结.values())[0])\n",
    "print(参数模板)\n",
    "# [ parse_url_qs_for_compTag(x)['compTag'] for x in 公司数据选择器链结.values()]\n",
    "[ parse_url_qs_for_compTag(x)['compTag'][0] for x in 公司数据选择器链结.values()]\n",
    "\n",
    "字典_compTag = { k:parse_url_qs_for_compTag(v)['compTag'][0] for k,v in 公司数据选择器链结.items()}\n",
    "print (字典_compTag)\n",
    "\n",
    "# 建构 参数模板  \n",
    "def 参数模板生成(compTag , keyword ):\n",
    "    参数 = 参数模板.copy()\n",
    "    参数['compTag'] = compTag\n",
    "    参数['keyword'] = keyword\n",
    "    return (参数)\n",
    "\n",
    "参数_compTag_用户体验 = { k:参数模板生成(compTag = [v], keyword = ['用户体验']) for k,v in 字典_compTag.items()}\n",
    "print(参数_compTag_用户体验)\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>scheme</th>\n",
       "      <th>netloc</th>\n",
       "      <th>path</th>\n",
       "      <th>params</th>\n",
       "      <th>query</th>\n",
       "      <th>fragment</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td>/zhaopin/</td>\n",
       "      <td></td>\n",
       "      <td>init=-1&amp;headckid=260c913c0571747b&amp;fromSearchBt...</td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td>/zhaopin/</td>\n",
       "      <td></td>\n",
       "      <td>init=-1&amp;headckid=260c913c0571747b&amp;fromSearchBt...</td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td>/zhaopin/</td>\n",
       "      <td></td>\n",
       "      <td>init=-1&amp;headckid=260c913c0571747b&amp;fromSearchBt...</td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td>/zhaopin/</td>\n",
       "      <td></td>\n",
       "      <td>init=-1&amp;headckid=260c913c0571747b&amp;fromSearchBt...</td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td>/zhaopin/</td>\n",
       "      <td></td>\n",
       "      <td>init=-1&amp;headckid=260c913c0571747b&amp;fromSearchBt...</td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td></td>\n",
       "      <td></td>\n",
       "      <td>/zhaopin/</td>\n",
       "      <td></td>\n",
       "      <td>init=-1&amp;headckid=260c913c0571747b&amp;fromSearchBt...</td>\n",
       "      <td></td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  scheme netloc       path params  \\\n",
       "0                /zhaopin/          \n",
       "1                /zhaopin/          \n",
       "2                /zhaopin/          \n",
       "3                /zhaopin/          \n",
       "4                /zhaopin/          \n",
       "5                /zhaopin/          \n",
       "\n",
       "                                               query fragment  \n",
       "0  init=-1&headckid=260c913c0571747b&fromSearchBt...           \n",
       "1  init=-1&headckid=260c913c0571747b&fromSearchBt...           \n",
       "2  init=-1&headckid=260c913c0571747b&fromSearchBt...           \n",
       "3  init=-1&headckid=260c913c0571747b&fromSearchBt...           \n",
       "4  init=-1&headckid=260c913c0571747b&fromSearchBt...           \n",
       "5  init=-1&headckid=260c913c0571747b&fromSearchBt...           "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "scheme      1\n",
      "netloc      1\n",
      "path        1\n",
      "params      1\n",
      "query       5\n",
      "fragment    1\n",
      "dtype: int64\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>init</th>\n",
       "      <th>headckid</th>\n",
       "      <th>fromSearchBtn</th>\n",
       "      <th>keyword</th>\n",
       "      <th>ckid</th>\n",
       "      <th>siTag</th>\n",
       "      <th>d_sfrom</th>\n",
       "      <th>d_ckId</th>\n",
       "      <th>d_curPage</th>\n",
       "      <th>d_pageSize</th>\n",
       "      <th>d_headId</th>\n",
       "      <th>curPage</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>-1</td>\n",
       "      <td>260c913c0571747b</td>\n",
       "      <td>2</td>\n",
       "      <td>PRD</td>\n",
       "      <td>260c913c0571747b°radeFlag=0</td>\n",
       "      <td>1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw</td>\n",
       "      <td>search_unknown</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>0</td>\n",
       "      <td>40</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>-1</td>\n",
       "      <td>260c913c0571747b</td>\n",
       "      <td>2</td>\n",
       "      <td>PRD</td>\n",
       "      <td>260c913c0571747b°radeFlag=0</td>\n",
       "      <td>1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw</td>\n",
       "      <td>search_unknown</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>0</td>\n",
       "      <td>40</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-1</td>\n",
       "      <td>260c913c0571747b</td>\n",
       "      <td>2</td>\n",
       "      <td>PRD</td>\n",
       "      <td>260c913c0571747b°radeFlag=0</td>\n",
       "      <td>1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw</td>\n",
       "      <td>search_unknown</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>0</td>\n",
       "      <td>40</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>-1</td>\n",
       "      <td>260c913c0571747b</td>\n",
       "      <td>2</td>\n",
       "      <td>PRD</td>\n",
       "      <td>260c913c0571747b°radeFlag=0</td>\n",
       "      <td>1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw</td>\n",
       "      <td>search_unknown</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>0</td>\n",
       "      <td>40</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-1</td>\n",
       "      <td>260c913c0571747b</td>\n",
       "      <td>2</td>\n",
       "      <td>PRD</td>\n",
       "      <td>260c913c0571747b°radeFlag=0</td>\n",
       "      <td>1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw</td>\n",
       "      <td>search_unknown</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>0</td>\n",
       "      <td>40</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>-1</td>\n",
       "      <td>260c913c0571747b</td>\n",
       "      <td>2</td>\n",
       "      <td>PRD</td>\n",
       "      <td>260c913c0571747b°radeFlag=0</td>\n",
       "      <td>1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw</td>\n",
       "      <td>search_unknown</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>0</td>\n",
       "      <td>40</td>\n",
       "      <td>917a54aacc3a11183fcafabd322be908</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  init          headckid fromSearchBtn keyword                         ckid  \\\n",
       "0   -1  260c913c0571747b             2     PRD  260c913c0571747b°radeFlag=0   \n",
       "1   -1  260c913c0571747b             2     PRD  260c913c0571747b°radeFlag=0   \n",
       "2   -1  260c913c0571747b             2     PRD  260c913c0571747b°radeFlag=0   \n",
       "3   -1  260c913c0571747b             2     PRD  260c913c0571747b°radeFlag=0   \n",
       "4   -1  260c913c0571747b             2     PRD  260c913c0571747b°radeFlag=0   \n",
       "5   -1  260c913c0571747b             2     PRD  260c913c0571747b°radeFlag=0   \n",
       "\n",
       "                                           siTag         d_sfrom  \\\n",
       "0  1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw  search_unknown   \n",
       "1  1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw  search_unknown   \n",
       "2  1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw  search_unknown   \n",
       "3  1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw  search_unknown   \n",
       "4  1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw  search_unknown   \n",
       "5  1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw  search_unknown   \n",
       "\n",
       "                             d_ckId d_curPage d_pageSize  \\\n",
       "0  917a54aacc3a11183fcafabd322be908         0         40   \n",
       "1  917a54aacc3a11183fcafabd322be908         0         40   \n",
       "2  917a54aacc3a11183fcafabd322be908         0         40   \n",
       "3  917a54aacc3a11183fcafabd322be908         0         40   \n",
       "4  917a54aacc3a11183fcafabd322be908         0         40   \n",
       "5  917a54aacc3a11183fcafabd322be908         0         40   \n",
       "\n",
       "                           d_headId curPage  \n",
       "0  917a54aacc3a11183fcafabd322be908       1  \n",
       "1  917a54aacc3a11183fcafabd322be908       2  \n",
       "2  917a54aacc3a11183fcafabd322be908       3  \n",
       "3  917a54aacc3a11183fcafabd322be908       4  \n",
       "4  917a54aacc3a11183fcafabd322be908       1  \n",
       "5  917a54aacc3a11183fcafabd322be908       9  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "init             1\n",
      "headckid         1\n",
      "fromSearchBtn    1\n",
      "keyword          1\n",
      "ckid             1\n",
      "siTag            1\n",
      "d_sfrom          1\n",
      "d_ckId           1\n",
      "d_curPage        1\n",
      "d_pageSize       1\n",
      "d_headId         1\n",
      "curPage          5\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "from urllib.parse import urlparse, parse_qs\n",
    "import pandas as pd\n",
    "from IPython.display import display, HTML\n",
    "\n",
    "df = pd.DataFrame([ urlparse(x) for x in href_列表])\n",
    "df_qs = pd.DataFrame([{k:v[0] for k,v in parse_qs(x).items()} for x in df['query'] ])\n",
    "\n",
    "display(df)\n",
    "print(df.nunique())\n",
    "display(df_qs)\n",
    "print(df_qs.nunique())\n",
    "\n",
    "df_qs.curPage\n",
    "df_qs = df_qs.assign (curPage_int=df_qs.curPage.astype(int)) # 变成整数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'init': ['-1'], 'headckid': ['260c913c0571747b'], 'fromSearchBtn': ['2'], 'keyword': ['PRD'], 'ckid': ['260c913c0571747b°radeFlag=0'], 'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'], 'd_sfrom': ['search_unknown'], 'd_ckId': ['917a54aacc3a11183fcafabd322be908'], 'd_curPage': ['0'], 'd_pageSize': ['40'], 'd_headId': ['917a54aacc3a11183fcafabd322be908'], 'curPage': ['1']}\n",
      "{'2': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=1', '3': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=2', '4': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=3', '5': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=4', '下一页': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=1', '': '/zhaopin/?init=-1&headckid=260c913c0571747b&fromSearchBtn=2&keyword=PRD&ckid=260c913c0571747b°radeFlag=0&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=917a54aacc3a11183fcafabd322be908&d_curPage=0&d_pageSize=40&d_headId=917a54aacc3a11183fcafabd322be908&curPage=9'}\n"
     ]
    }
   ],
   "source": [
    "def parse_url_qs_for_curPage (url):\n",
    "    six_parts = urlparse(url) \n",
    "    out = parse_qs(six_parts.query)\n",
    "    return (out)\n",
    "\n",
    "参数模板 = parse_url_qs_for_curPage(href_列表[0])\n",
    "print (参数模板)\n",
    "\n",
    "print (href_字典)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "9\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{0: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [0]},\n",
       " 1: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [1]},\n",
       " 2: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [2]},\n",
       " 3: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [3]},\n",
       " 4: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [4]},\n",
       " 5: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [5]},\n",
       " 6: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [6]},\n",
       " 7: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [7]},\n",
       " 8: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [8]},\n",
       " 9: {'init': ['-1'],\n",
       "  'headckid': ['260c913c0571747b'],\n",
       "  'fromSearchBtn': ['2'],\n",
       "  'keyword': ['用户体验'],\n",
       "  'ckid': ['260c913c0571747b°radeFlag=0'],\n",
       "  'siTag': ['1B2M2Y8AsgTpgAmY7PhCfg~fA9rXquZc5IkJpXC-Ycixw'],\n",
       "  'd_sfrom': ['search_unknown'],\n",
       "  'd_ckId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'd_curPage': ['0'],\n",
       "  'd_pageSize': ['40'],\n",
       "  'd_headId': ['917a54aacc3a11183fcafabd322be908'],\n",
       "  'curPage': [9]}}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def 参数模板生成(keyword, curPage):\n",
    "    参数 = 参数模板.copy()\n",
    "    参数['curPage'] = curPage\n",
    "    参数['keyword'] = keyword\n",
    "    return (参数)\n",
    "\n",
    "参数_keyword_用户体验_curPage = { \n",
    "    i:参数模板生成(curPage = [i], \\\n",
    "                  keyword = ['用户体验']) \\\n",
    "    for i,v in href_字典.items()\\\n",
    "    }\n",
    "\n",
    "\n",
    "\n",
    "print (df_qs.curPage_int.min()) \n",
    "print (df_qs.curPage_int.max()) \n",
    "\n",
    "\n",
    "参数_keyword_用户体验_curPage = { \n",
    "    i:参数模板生成(curPage = [i], \\\n",
    "                  keyword = ['用户体验']) \\\n",
    "    for i in range(0,df_qs.curPage_int.max()+1)\\\n",
    "    }\n",
    "参数_keyword_用户体验_curPage"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "  \n",
    "```python\n",
    "\n",
    "url = \"https://www.liepin.com/zhaopin/\"\n",
    "\n",
    "list_df = list()\n",
    "for k,v in 参数_compTag_用户体验.items():\n",
    "    payload = v\n",
    "    df = requests_liepin( url, params = payload)\n",
    "    df = df.assign (热门公司类型 = k)    \n",
    "    list_df.append(df)\n",
    "\n",
    "df_all = pd.concat(list_df)\n",
    "df_all\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "session = HTMLSession()\n",
    "\n",
    "def requests_liepin( url, params):\n",
    "    r = session.get( url , params = payload)\n",
    "\n",
    "    \n",
    "    主要元素 = r.html.xpath( '//ul[@class=\"sojob-list\"]/li')\n",
    "\n",
    "    dict_xpaths={ \n",
    "        'text': {\n",
    "            'edu':      '//div[contains(@class,\"job-info\")]/p/span[@class=\"edu\"]',\n",
    "            '经验':      '//div[contains(@class,\"job-info\")]/p/span[@class=\"edu\"]/following-sibling::span',\n",
    "            '薪水':    '//div[contains(@class,\"job-info\")]/p/span[@class=\"text-warning\"]', \n",
    "            '时间':    '//div[contains(@class,\"job-info\")]/p/time/@title', \n",
    "            '职称':    '//div[contains(@class,\"job-info\")]/h3/a', \n",
    "            '公司地点': '//div[contains(@class,\"job-info\")]/p/a',\n",
    "            '公司名称': '//div[contains(@class,\"sojob-item-main\")]//p[@class=\"company-name\"]/a', \n",
    "        },\n",
    "        'text_content': {\n",
    "        },\n",
    "        'href': {\n",
    "            '链结':    '//div[contains(@class,\"job-info\")]/h3/a', \n",
    "            '公司URL': '//div[contains(@class,\"sojob-item-main\")]//p[@class=\"company-name\"]/a', \n",
    "        }\n",
    "    }\n",
    "\n",
    "    def get_e_text_content(_xpath_):\n",
    "        暂存结果 = [e.xpath(_xpath_)[0].lxml.text_content() for e in 主要元素]\n",
    "        return(暂存结果)\n",
    "\n",
    "    def get_e_text(_xpath_):\n",
    "        暂存结果 = [\"\".join([x.strip() if type(x) is str else x.text.strip() for x in e.xpath(_xpath_)]) for e in 主要元素]\n",
    "        return(暂存结果)\n",
    "\n",
    "    def get_e_href(_xpath_):\n",
    "        暂存结果 = [list(e.xpath(_xpath_, first=True).absolute_links)[0] \\\n",
    "                   if len(e.xpath(_xpath_, first=True).absolute_links) >= 1  \\\n",
    "                   else \"\" for e in 主要元素]\n",
    "        return(暂存结果)\n",
    "\n",
    "    数据字典 = dict()\n",
    "\n",
    "    数据字典 = {k:get_e_text_content(v) for k,v in dict_xpaths['text_content'].items()}\n",
    "    数据字典.update({k:get_e_text(v) for k,v in dict_xpaths['text'].items()})\n",
    "    数据字典.update({k:get_e_href(v) for k,v in dict_xpaths['href'].items()})\n",
    "\n",
    "    数据 = pd.DataFrame(数据字典)\n",
    "    return (数据)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 爬亦有道- 不要爬太快\n",
    "time.sleep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 4.6 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "time.sleep(3+4*random())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>edu</th>\n",
       "      <th>经验</th>\n",
       "      <th>薪水</th>\n",
       "      <th>时间</th>\n",
       "      <th>职称</th>\n",
       "      <th>公司地点</th>\n",
       "      <th>公司名称</th>\n",
       "      <th>链结</th>\n",
       "      <th>公司URL</th>\n",
       "      <th>curPage</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>本科及以上</td>\n",
       "      <td>7年以上</td>\n",
       "      <td>面议</td>\n",
       "      <td>2020年04月04日</td>\n",
       "      <td>营销副总（项目）</td>\n",
       "      <td>佛山</td>\n",
       "      <td>中国电建地产集团华南区域总部</td>\n",
       "      <td>https://www.liepin.com/job/1927229275.shtml</td>\n",
       "      <td>https://www.liepin.com/company/9624513/</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>本科及以上</td>\n",
       "      <td>7年以上</td>\n",
       "      <td>面议</td>\n",
       "      <td>2020年04月04日</td>\n",
       "      <td>营销副总（项目）</td>\n",
       "      <td>广州-石井</td>\n",
       "      <td>中国电建地产集团华南区域总部</td>\n",
       "      <td>https://www.liepin.com/job/1927229273.shtml</td>\n",
       "      <td>https://www.liepin.com/company/9624513/</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>本科及以上</td>\n",
       "      <td>7年以上</td>\n",
       "      <td>面议</td>\n",
       "      <td>2020年04月04日</td>\n",
       "      <td>营销副总（项目）</td>\n",
       "      <td>深圳</td>\n",
       "      <td>中国电建地产集团华南区域总部</td>\n",
       "      <td>https://www.liepin.com/job/1927229271.shtml</td>\n",
       "      <td>https://www.liepin.com/company/9624513/</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>本科及以上</td>\n",
       "      <td>1年以上</td>\n",
       "      <td>10-12k·13薪</td>\n",
       "      <td>2020年04月04日</td>\n",
       "      <td>c++开发工程师</td>\n",
       "      <td>北京</td>\n",
       "      <td>北京赛普泰克技术有限公司</td>\n",
       "      <td>https://www.liepin.com/job/1927229255.shtml</td>\n",
       "      <td>https://www.liepin.com/company/7884122/</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>统招本科</td>\n",
       "      <td>6年以上</td>\n",
       "      <td>15-25k·16薪</td>\n",
       "      <td>2020年04月04日</td>\n",
       "      <td>干部管理经理</td>\n",
       "      <td>深圳</td>\n",
       "      <td>华星光电</td>\n",
       "      <td>https://www.liepin.com/job/1927228767.shtml</td>\n",
       "      <td>https://www.liepin.com/company/671058/</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>35</th>\n",
       "      <td>大专及以上</td>\n",
       "      <td>2年以上</td>\n",
       "      <td>6-10k·12薪</td>\n",
       "      <td>2020年04月03日</td>\n",
       "      <td>人力资源专员/招聘</td>\n",
       "      <td>宁波-鄞州区</td>\n",
       "      <td>宁波渠成集团有限公司</td>\n",
       "      <td>https://www.liepin.com/job/1925226785.shtml</td>\n",
       "      <td>https://www.liepin.com/company/8096424/</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>36</th>\n",
       "      <td>统招本科</td>\n",
       "      <td>经验不限</td>\n",
       "      <td>8-15k·14薪</td>\n",
       "      <td>2020年04月03日</td>\n",
       "      <td>卫星电源控制器研发工程师</td>\n",
       "      <td>苏州-虎丘区</td>\n",
       "      <td>苏州馥昶空间技术有限公司</td>\n",
       "      <td>https://www.liepin.com/job/1925224865.shtml</td>\n",
       "      <td>https://www.liepin.com/company/9665557/</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>37</th>\n",
       "      <td>本科及以上</td>\n",
       "      <td>3年以上</td>\n",
       "      <td>面议</td>\n",
       "      <td>2020年04月03日</td>\n",
       "      <td>销售部销售经理</td>\n",
       "      <td>上海</td>\n",
       "      <td>上海大丁自动化科技有限公司</td>\n",
       "      <td>https://www.liepin.com/job/1925196603.shtml</td>\n",
       "      <td>https://www.liepin.com/company/10058443/</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>38</th>\n",
       "      <td>大专及以上</td>\n",
       "      <td>2年以上</td>\n",
       "      <td>5-8k·12薪</td>\n",
       "      <td>2020年04月03日</td>\n",
       "      <td>ie工程师</td>\n",
       "      <td>中山</td>\n",
       "      <td>中山市皇鼎五金制品有限公司</td>\n",
       "      <td>https://www.liepin.com/job/1925097067.shtml</td>\n",
       "      <td>https://www.liepin.com/company/9190284/</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>39</th>\n",
       "      <td>本科及以上</td>\n",
       "      <td>3年以上</td>\n",
       "      <td>7-20k·12薪</td>\n",
       "      <td>2020年04月03日</td>\n",
       "      <td>广告销售经理</td>\n",
       "      <td>上海-长宁区</td>\n",
       "      <td>上海魄力广告传媒有限公司</td>\n",
       "      <td>https://www.liepin.com/job/1925095091.shtml</td>\n",
       "      <td>https://www.liepin.com/company/8239390/</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>400 rows × 10 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      edu    经验          薪水           时间            职称    公司地点  \\\n",
       "0   本科及以上  7年以上          面议  2020年04月04日      营销副总（项目）      佛山   \n",
       "1   本科及以上  7年以上          面议  2020年04月04日      营销副总（项目）   广州-石井   \n",
       "2   本科及以上  7年以上          面议  2020年04月04日      营销副总（项目）      深圳   \n",
       "3   本科及以上  1年以上  10-12k·13薪  2020年04月04日      c++开发工程师      北京   \n",
       "4    统招本科  6年以上  15-25k·16薪  2020年04月04日        干部管理经理      深圳   \n",
       "..    ...   ...         ...          ...           ...     ...   \n",
       "35  大专及以上  2年以上   6-10k·12薪  2020年04月03日     人力资源专员/招聘  宁波-鄞州区   \n",
       "36   统招本科  经验不限   8-15k·14薪  2020年04月03日  卫星电源控制器研发工程师  苏州-虎丘区   \n",
       "37  本科及以上  3年以上          面议  2020年04月03日       销售部销售经理      上海   \n",
       "38  大专及以上  2年以上    5-8k·12薪  2020年04月03日         ie工程师      中山   \n",
       "39  本科及以上  3年以上   7-20k·12薪  2020年04月03日        广告销售经理  上海-长宁区   \n",
       "\n",
       "              公司名称                                           链结  \\\n",
       "0   中国电建地产集团华南区域总部  https://www.liepin.com/job/1927229275.shtml   \n",
       "1   中国电建地产集团华南区域总部  https://www.liepin.com/job/1927229273.shtml   \n",
       "2   中国电建地产集团华南区域总部  https://www.liepin.com/job/1927229271.shtml   \n",
       "3     北京赛普泰克技术有限公司  https://www.liepin.com/job/1927229255.shtml   \n",
       "4             华星光电  https://www.liepin.com/job/1927228767.shtml   \n",
       "..             ...                                          ...   \n",
       "35      宁波渠成集团有限公司  https://www.liepin.com/job/1925226785.shtml   \n",
       "36    苏州馥昶空间技术有限公司  https://www.liepin.com/job/1925224865.shtml   \n",
       "37   上海大丁自动化科技有限公司  https://www.liepin.com/job/1925196603.shtml   \n",
       "38   中山市皇鼎五金制品有限公司  https://www.liepin.com/job/1925097067.shtml   \n",
       "39    上海魄力广告传媒有限公司  https://www.liepin.com/job/1925095091.shtml   \n",
       "\n",
       "                                       公司URL  curPage  \n",
       "0    https://www.liepin.com/company/9624513/        0  \n",
       "1    https://www.liepin.com/company/9624513/        0  \n",
       "2    https://www.liepin.com/company/9624513/        0  \n",
       "3    https://www.liepin.com/company/7884122/        0  \n",
       "4     https://www.liepin.com/company/671058/        0  \n",
       "..                                       ...      ...  \n",
       "35   https://www.liepin.com/company/8096424/        9  \n",
       "36   https://www.liepin.com/company/9665557/        9  \n",
       "37  https://www.liepin.com/company/10058443/        9  \n",
       "38   https://www.liepin.com/company/9190284/        9  \n",
       "39   https://www.liepin.com/company/8239390/        9  \n",
       "\n",
       "[400 rows x 10 columns]"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "import time\n",
    "from random import random\n",
    "\n",
    "url = \"https://www.liepin.com/zhaopin/\"\n",
    "\n",
    "list_df = list()\n",
    "for k,v in 参数_keyword_用户体验_curPage.items():\n",
    "    payload = v\n",
    "    df = requests_liepin( url, params = payload)\n",
    "    time.sleep(3+4*random())  \n",
    "    df = df.assign (curPage = k)  # 区分  curPage\n",
    "    list_df.append(df)\n",
    "\n",
    "df_all = pd.concat(list_df).reset_index()\n",
    "df_all.index.name = '序'\n",
    "\n",
    "# 输出\n",
    "df_all.to_excel(\"20春_Web数据挖掘_week04_liepin_翻页.xlsx\",\\\n",
    "                sheet_name=\"用户体验\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "time.sleep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "用户体验 10\n",
      "UX 10\n",
      "Wall time: 1min 54s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "import time\n",
    "from random import random\n",
    "\n",
    "url = \"https://www.liepin.com/zhaopin/\"\n",
    "xpath_翻页a = '//div[@class=\"pagerbar\"]/a[starts-with(@href,\"/zhaopin\")]'\n",
    "\n",
    "keywords = ['用户体验','UX']\n",
    "list_df = list()\n",
    "\n",
    "\n",
    "for key in keywords:\n",
    "    payload = 参数模板生成(keyword=[key], curPage=['0'])\n",
    "    df = requests_liepin( url, params = payload)\n",
    "    href_列表 = [x.xpath('//@href')[0] for x in r.html.xpath(xpath_翻页a)]\n",
    "    df = pd.DataFrame([ urlparse(x) for x in href_列表])\n",
    "    df_qs = pd.DataFrame([{k:v[0] for k,v in parse_qs(x).items()} for x in df['query'] ])\n",
    "    df_qs = df_qs.assign (curPage_int=df_qs.curPage.astype(int)) \n",
    "    长度 = df_qs.curPage_int.max()+1\n",
    "    参数_keyword_X_curPage = { \n",
    "        i:参数模板生成(curPage = [i], \\\n",
    "                      keyword = [key]) \\\n",
    "        for i in range(0,长度)\\\n",
    "        }\n",
    "    #print (参数_keyword_X_curPage)\n",
    "    print (key,长度)\n",
    "    \n",
    "    for k,v in 参数_keyword_X_curPage.items():\n",
    "        payload = v\n",
    "        df = requests_liepin( url, params = payload)\n",
    "        time.sleep(3+4*random()) \n",
    "        df = df.assign (keyword = key)  \n",
    "        df = df.assign (curPage = k)  \n",
    "        list_df.append(df)\n",
    "        \n",
    "df_all = pd.concat(list_df).reset_index()\n",
    "df_all.index.name = '序'\n",
    "\n",
    "df_all.to_excel(\"20春_Web数据挖掘_week04_liepin_翻页.xlsx\",\\\n",
    "                sheet_name=\"_\".join(keywords))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 翻页：数据备份与整合\n",
    "多个页面+多个关键词执行时，若怕中断最好把每一页的df内容备份做中继"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "用户体验 10\n",
      "UX 10\n",
      "产品需求 10\n",
      "PRD 10\n",
      "Wall time: 3min 54s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "import time\n",
    "from random import random\n",
    "\n",
    "url = \"https://www.liepin.com/zhaopin/\"\n",
    "xpath_翻页a = '//div[@class=\"pagerbar\"]/a[starts-with(@href,\"/zhaopin\")]'\n",
    "\n",
    "keywords = ['用户体验','UX','产品需求','PRD']\n",
    "list_df = list()\n",
    "\n",
    "for key in keywords:\n",
    "    payload = 参数模板生成(keyword=[key], curPage=['0'])\n",
    "    df = requests_liepin( url, params = payload)\n",
    "    href_列表 = [x.xpath('//@href')[0] for x in r.html.xpath(xpath_翻页a)]\n",
    "    df = pd.DataFrame([ urlparse(x) for x in href_列表])\n",
    "    df_qs = pd.DataFrame([{k:v[0] for k,v in parse_qs(x).items()} for x in df['query'] ])\n",
    "    df_qs = df_qs.assign (curPage_int=df_qs.curPage.astype(int)) # 变成整数\n",
    "    长度 = df_qs.curPage_int.max()+1\n",
    "    参数_keyword_X_curPage = { \n",
    "        i:参数模板生成(curPage = [i], \\\n",
    "                      keyword = [key]) \\\n",
    "        for i in range(0,长度)\\\n",
    "        }\n",
    "    #print (参数_keyword_X_curPage)\n",
    "    print (key,长度)\n",
    "    \n",
    "    for k,v in 参数_keyword_X_curPage.items():\n",
    "        payload = v\n",
    "        df = requests_liepin( url, params = payload)\n",
    "        time.sleep(3+4*random())  #放慢脚步 3-7秒, 平均约5秒\n",
    "        ## 备份\n",
    "        df.to_csv(\"20春_Web数据挖掘_week04_liepin_{key}_{k}.tsv\"\\\n",
    "                  .format(key=key, k=k), sep=\"\\t\", encoding=\"utf8\")\n",
    "        \n",
    "        df = df.assign (keyword = key)  # 区分  keyword    \n",
    "        df = df.assign (curPage = k)  # 区分  curPage    \n",
    "        list_df.append(df)\n",
    "        \n",
    "df_all = pd.concat(list_df).reset_index()\n",
    "df_all.index.name = '序'\n",
    "\n",
    "df_all.to_excel(\"20春_Web数据挖掘_week04_liepin_翻页_4.xlsx\",\\\n",
    "                sheet_name=\"_\".join(keywords))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'i' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-1-e3697a116898>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0murl\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m\"https://m.liepin.com/zhaopin/pn\"\u001b[0m\u001b[1;33m+\u001b[0m\u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0murl\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0msession\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mHTMLSession\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m data ={\n",
      "\u001b[1;31mNameError\u001b[0m: name 'i' is not defined"
     ]
    }
   ],
   "source": [
    "url = \"https://m.liepin.com/zhaopin/pn\"+str(i)\n",
    "print(url)\n",
    "session = HTMLSession()\n",
    "\n",
    "data ={\n",
    "    \"compScale\":\"000\",\n",
    "    \"jobkind\":\"\",\n",
    "    \"salaryhigh\":\"999\",\n",
    "    \"compKind\":\"000\",\n",
    "    \"industrys\":\"000\",\n",
    "    \"pubtime\":\"000\",\n",
    "    \"dqs\":\"050020\",  # 省份。例如：广州：dqs=050020\n",
    "    \"keyword\":\"python\", # 行业\n",
    "    \"salarylow\":\"0\",\n",
    "    \"degradeFlag\":\"0\",\n",
    "}\n",
    "\n",
    "\n",
    "\n",
    "r = session.get( url , params = data )\n",
    "\n",
    "\n",
    "current_pn = int(r.html.xpath('//div/p[contains(@class,\"pager-count\")]/span[1]/text()')[0])\n",
    "\n",
    "max_pn = int(r.html.xpath('//div/p[contains(@class,\"pager-count\")]/span[2]/text()')[0])\n",
    "print(\"当前页\",current_pn,type(current_pn))\n",
    "print(\"最后一页\",max_pn,type(max_pn))\n",
    "\n",
    "# 循环所有页码\n",
    "\n",
    "content_list = []\n",
    "数据字典 = {}\n",
    "dict_xpaths={ \n",
    "'职称':    './/ul/li/a[contains(@class,\"job-name\")]/span[@class=\"name-text\"]/text()', \n",
    "'链结':    './/ul/li/a[contains(@class,\"job-name\")]/@href', \n",
    "'薪水':    './/ul/li/a[contains(@class,\"job-name\")]/following-sibling::span/text()', \n",
    "'公司地点':'.//ul/li/time/following-sibling::a/text()',\n",
    "'公司名称': './/ul/li/a[contains(@class,\"company-name\")]/text()', \n",
    "'时间':    './/ul/li/time/text()', \n",
    "#    '公司URL': './/ul/li/a[contains(@class,\"company-name\")]/@href', \n",
    "#    '经验':      './/ul/li/a/following-sibling::text()'\n",
    "}\n",
    "for i in range(max_pn):\n",
    "\n",
    "    url = \"https://m.liepin.com/zhaopin/pn\"+str(i)\n",
    "    r = session.get( url , params = data )\n",
    "    print(url)\n",
    "\n",
    "    数据字典 ={k:r.html.xpath(v) for k,v in dict_xpaths.items()}\n",
    "\n",
    "    content_list.append(数据字典)\n",
    "content_list[0]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "749px",
    "left": "1125.609375px",
    "top": "110px",
    "width": "281.390625px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
